%% -*- coding: latin-1 -*-
%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     MySQL 管理模块
%%% @end
%%%-------------------------------------------------------------------
-module(db_mysql_mod).

-export([ver_upgrade/1]).

-include("common.hrl").


%%%===================================================================
%%% API
%%%===================================================================

ver_upgrade([]) ->
    ok;
ver_upgrade([Db | Dbs]) ->
    Name = util_type:list_to_atom(lists:concat(["mysql_", Db])),
    ver_init(Db, Name),

    case get_db_ver(Name) of
        {ok, [Ver]} ->
            upgrade(Db, Name, Ver + 1);
        {error, Reason} ->
            erlang:throw({error, Reason})
    end,

    ver_upgrade(Dbs).


%%%===================================================================
%%% Internal functions
%%%===================================================================

ver_init(Db, Name) ->
    case get_db_ver(Name) of
        {ok, _Ver} -> ok;
        _ ->
            case ver_init_db(Db, Name) of
                ok ->
                    ?INFO("MySQL init [~p] version success", [Db]),
                    ok;
                {error, Reason} ->
                    erlang:throw({error, Reason})
            end
    end.

ver_init_db(Db, Name) ->
    ?INFO("MySQL init [~p] version", [Db]),
    case get_ver(Db, 1) of
        false -> ok;
        Sql ->
            case mysql:query(Name, Sql) of
                ok ->
                    case mysql:query(Name, get_ver(Db, {insert_ver, 1})) of
                        ok ->
                            ok;
                        {error, Reason} ->
                            {error, db_mysql:error_message(Reason)}
                    end;
                {error, Reason} ->
                    {error, db_mysql:error_message(Reason)}
            end
    end.

%% 更新版本
upgrade(Db, Name, Ver) ->
    case get_ver(Db, Ver) of
        false ->
            ?INFO("MySQL update [~p] version success, new version:~w", [Db, Ver - 1]),
            ok;
        Sql ->
            case mysql:query(Name, Sql) of
                ok ->
                    case mysql:query(Name, get_ver(Db, {update_ver, Ver})) of
                        ok ->
                            upgrade(Db, Name, Ver + 1);
                        {error, Reason} ->
                            ?ERR("MySQL update [~p] version error, version:~w, reason:~n~p", [Db, Ver, db_mysql:error_message(Reason)])
                    end;
                {error, Reason} ->
                    ?ERR("MySQL update [~p] version error, version:~w, reason:~n~p", [Db, Ver, db_mysql:error_message(Reason)])
            end
    end.


%%%===================================================================
%%% MySQL 相关
%%%===================================================================

%% 获取版本
get_db_ver(Name) ->
    case mysql:query(Name, "SELECT `ver` FROM `version`") of
        {ok, _ColumnNames, [Ver]} -> {ok, Ver};
        _ -> {error, not_found}
    end.

%% 插入或更新版本
get_ver(_Db, {insert_ver, Ver}) ->
    io_lib:format("INSERT INTO `version` (`ver`) VALUES (~w)", [Ver]);
get_ver(_Db, {update_ver, Ver}) ->
    io_lib:format("UPDATE `version` SET `ver`=~w", [Ver]);

%% 数据版本控制
get_ver(_Db, 1) ->
"
CREATE TABLE `version` (
  `ver` smallint(5) UNSIGNED NOT NULL COMMENT '版本',
  PRIMARY KEY (`ver`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='版本';
";
get_ver(core, 2) ->
"
CREATE TABLE `adm_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `account` varchar(32) NOT NULL COMMENT '帐号',
  `password` char(32) NOT NULL COMMENT '密码',
  `type` tinyint(3) unsigned NOT NULL COMMENT '类型 1:管理员|11:游客',
  `remark` text NOT NULL COMMENT '备注',

  `locked` tinyint(3) unsigned NOT NULL DEFAULT 0 COMMENT '是否被锁定 0:否|1:是',

  `login_at` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '登录时间',
  `login_ip` char(15) NOT NULL DEFAULT '' COMMENT '登录IP',
  `login_times` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '登录次数',
  PRIMARY KEY (`id`),
  UNIQUE KEY `account` (`account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理员用户';
";
get_ver(core, 3) ->
"
INSERT INTO `adm_user` VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 1, 'admin', 0, 0, '', 0);
INSERT INTO `adm_user` VALUES (2, 'guest', '084e0343a0486ff05530df6c705c8bb4', 11, 'guest', 0, 0, '', 0);
";

get_ver(core, 4) ->
    false.
